Qt.include("./Promise.js")
function getQueryUri(query) {
    let uri = ""
    let init = true
    for (let key in query) {
        uri += `${init ? '?' : '&'}${key}=${query[key]}`
        init = false
    }
    return uri
}
function request(url, query, data, method, setHeader) {
    const task = (res, rej) => {
        if (typeof query == 'object' && query) {
            url += getQueryUri(query)
        }
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE)
            return
            if (xhr.status !== 200) {
                // print("request获取到数据"+xhr.responseText)
                rej(xhr.status)
                return
            }
            // print("request获取到数据")
            if (xhr.getResponseHeader('content-type').includes(
                    'application/json'))
            res(JSON.parse(xhr.responseText))
            else
            res(xhr.responseText)
        }
        // print("request获取数据:+"+url)
        xhr.open(method, url, true)
        if (setHeader) {
            setHeader(xhr)
        }
        xhr.send()
    }
    return new Promise(task)
}

function get(url, query) {
    return request(url, query, null, "GET")
}
function post(url, data, query) {
    const setHeader = xhr => {
        xhr.setRequestHeader("content-type", "application/json")
    }
    return request(url, query, data, "POST", setHeader)
}
function put(url, data, query) {
    const setHeader = xhr => {
        xhr.setRequestHeader("content-type", "application/json")
    }
    return request(url, query, data, "PUT", setHeader)
}
